//File Viewer Program for PCMod (SERVER)

PROG.PName = "FileViewer"
PROG.Author = "[GU]|ZLC|thomasfn"

function PROG:Initialize( pl )
	SendClientProgram( pl, "FileViewer" )
	SendClientWindow( pl, "Main" )
	
	self:PC_Changed( pl )
end

function PROG:PC_Changed( pl )
	// See if the player has actually used the PC
	pc = pl.CurrentPC
	if (!pc) then return end
	
	// Store the PC info
	self.PC = pc
	self.PCID = pc:EntIndex()
	
	// Init some vars on the PC
	if (!PData[self.PCID]) then PData[self.PCID] = {} end
	if (!PData[self.PCID].Files) then PData[self.PCID].Files = {} end
	
	
end

function PROG:Unload()
	
end

function PROG:Think()

end

function PROG:CommandRecieved( ply, command, args )
	local pc = ply.CurrentPC
	// Msg( "Command: " .. command .. "\n" )
	if (command == "read_structure") then
		if (args[1]) then self:BeamStructure( ply, args[1] ) end
		// self:BeamStructure( ply, "/" )
		// Msg( "Sending structure...\n" )
	end
	if (command == "read_files") then
		if (args[1]) then self:BeamFilelist( ply, args[1] ) end
		Msg( "Sending files...\n" )
	end
	if (command == "quit") then
		UnloadProgram( ply )
	end
end

function PROG:BeamStructure( ply, dir )
	Msg( "Beaming " .. dir .. "!\n" )
	local pc = ply.CurrentPC
	if (!pc) then
		Msg("No PC!\n")
		return
	end
	local fls = pc.Data[ pc:EntIndex() ].Files
	local tst = "root" .. dir
	local tmp = {}
	local tmp3 = {}
	// Msg (tst .. "\n" )
	for k, v in pairs( fls ) do
		// Msg ("Checking " .. k .. "\n" )
		// if (v) then Msg (tostring(#v) .. " files in dir!\n" ) end
		local stra = string.Explode( "/", k )
		local strb = string.Explode( "/", tst )
		if ((string.Left( k, string.len( tst ) ) == tst) && (#stra==#strb) && (k != tst)) then
			local val = string.sub( k, string.len( tst )+1 )
			table.insert( tmp, val )
			// Msg( "Check!\n" )
			local tmp2 = stra
			table.remove( tmp2, 1 )
			table.insert( tmp3, "/" .. table.concat( tmp2, "/" ) .. "/" )
		end
	end
	if ((!tmp) || (#tmp == 0)) then return end
	umsg.Start( "_pcmod_filestructure", ply )
		umsg.String( dir )
		umsg.Short( #tmp )
		for _, v in pairs( tmp ) do
			umsg.String( v )
		end
	umsg.End()
	self:BeamFilelist( ply, dir )
	for _, v in pairs( tmp3 ) do
		self:BeamStructure( ply, v )
	end
	
end

function PROG:BeamFilelist( ply, dir )
	local pc = ply.CurrentPC
	if (!pc) then
		Msg("No PC!\n")
		return
	end
	local fls = pc.Data[ pc:EntIndex() ].Files
	local dr = fls[ "root" .. dir ]
	// local dr = fls[ "root/Documents" ]
	Msg( "Preparing to send files: " .. dir .. "\n" )
	if (!dr) then
		Msg( "No node! (root" .. dir .. "\n" )
		return
	end
	Msg( "Sending files: " .. dir .. "\n" )
	umsg.Start( "_pcmod_filelist", ply )
		umsg.String( dir )
		umsg.Short( table.Count(dr) )
		for k, v in pairs( dr ) do
			umsg.String( k )
		end
	umsg.End()
end

function PROG:PacketRecieved( packet, pc )
	
end